var WxParse = require('../../wxParse/wxParse.js');
const {countDown} = require('../../utils/util.js');
//获取应用实例
var app = getApp();
const bgMusicAudioContext = wx.getBackgroundAudioManager()
Page({
  data: {
    imgUrl: app.globalData.domin,
    regionValue: [], //省市
    showRegion: false, //省市
    isShowVideo: false,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    isShowModal: false,
    buyNumber: 1,
    modalOperaType: "",
    cartNumber: 0,
    goodDetail: {},
    chooseGuige: {},
    videoShow: false,
    isShowshare: false,
    intoView: 'part1',
    curPart: 'part1',
    curshow: 'goodintro',
    isShowposter: false,
    goodType: 'good',
    isShowOrdertip: true,
    province: '', //省
    city: '', //市区
    district: '', //乡镇
    town:'',
    goodId: 0, //商品id
    em: 0,
    remainNum:0,//库存
    countdownTimer:null,    //倒计时timer
    isShowCountdown:false,  //是否显示倒计时
    countdownTime:"0天0小时0分钟0秒",       //倒计时字符串
    ticketShow:false,
    ticketList:[],
    need_time_picker:null ,//是否需要日期选择
    month_price:null ,//对应日期对应的价格库存
    orderParameter:null,//门票信息
    show:false, //时间选择器，
    currentYear:null,
    dateOfUse:null,
    in:null,
    ticketI:0,
    dataI:0,
    selection:{
      date:'更多',
      price:'时间'
    },
    name:'',
    price:'',
    area:null,
    playtime:null
  },
  onUnload(){
    this.data.countdownTimer&&clearInterval(this.data.countdownTimer);
  },
  //商品时间选择
  TimeSelection() {
    let myDate = new Date();
    let time = myDate.toLocaleDateString()
    time = time.split('/')
    let selection={
      date:'选择',
      price:'日期'
    }
    var obj= {
      currentYear:time[0],
      currentMonth:time[1],
      currentDay:time[2],
      nowYear:time[0],
      nowMonth: time[1]
    }

    this.setData({
      need_time_picker:true,
      modalOperaType: "buy",
      buyNumber: 1,
      currentYear:obj,
      dateOfUse:null,
      in:time[2],
      selection
    })

    
    // console.log(obj)
    // _this.setData({
    //   month_price:arr,
    //   currentYear:obj,
    //   modalOperaType: "buy",
    //   dateOfUse:dateOfUse,
    //   in:null
    // })
    console.log('need_time_picker',myDate.toLocaleDateString( ))
  },
  //门票订购
  ordernow(e) {
    console.log('门票订购',e.currentTarget.dataset.item.need_datetime_picker)
    let need_datetime_picker = e.currentTarget.dataset.item.need_datetime_picker
    let orderParameter = e.currentTarget.dataset.item
    let goodDetail= this.data.goodDetail
    
    if(orderParameter.user_price!==null&&orderParameter.user_price > 0) {
      goodDetail.price = orderParameter.user_price
    }else {
      goodDetail.price = orderParameter.price
    }
    goodDetail.name = e.currentTarget.dataset.item.title
    if(need_datetime_picker==true) {
      this.TimeSelector(e.currentTarget.dataset.item.uuid)
    } 
    this.setData({
      need_time_picker:need_datetime_picker,
      goodDetail:goodDetail,
      orderParameter: e.currentTarget.dataset.item,
      isShowModal: true,
      modalOperaType: "buy",
      buyNumber: 1,
      in:null
    })
  },
  //时间见选择数据
  TimeSelector(uuid) {
    let _this = this
    let data = {
      map:'applet_goods_ticket_price',
      gid: _this.data.goodId,
      uuid:uuid
    }
    let arr = []
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        console.log('票付通接口时间悬着起',res.data.data)
        let month_price = res.data.data
        let dateOfUse = {//时间选择器
          date:'今天',
          price:month_price[0].retail_price,
          data:month_price[0].date,
          day:month_price[0].date.split('-')[2]
        }
        console.log('dateOfUse',dateOfUse)
        for(let i = 0 ;i <month_price.length;i++) {
          let obj1={}
          obj1.price =month_price[i].retail_price
          obj1.months = month_price[i].date.split('-')[1]
          obj1.day = month_price[i].date.split('-')[2]
          arr.push(obj1)
        }
        var obj= {
          currentYear:month_price[0].date.split('-')[0],
          currentMonth:month_price[0].date.split('-')[1],
          nowYear:month_price[month_price.length-1].date.split('-')[0],
          nowMonth: month_price[month_price.length-1].date.split('-')[1]
        }
        console.log(obj)
        _this.setData({
          month_price:arr,
          currentYear:obj,
          modalOperaType: "buy",
          dateOfUse:dateOfUse,
          in:null
        })
      }
    })
  },
  //票付通获取门票信息
  getTickets() {
    let that = this
    let data = {
      map:'applet_goods_ticket_list',
      gid: that.data.goodId
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        console.log('门票信息',res.data)
        
        if(res.data.ec==200) {
          that.setData({
            ticketShow: true,
            ticketList: res.data.data
          })
          console.log(that.data.ticketShow)
        }else {
          that.setData({
            ticketShow: false
          })
        }
      }
    });
  },
  //设置下架倒计时
  setCountdownTimer(){
    
    let {autoOffTime} = this.data.goodDetail;
    console.log('下架时间',autoOffTime)
    // autoOffTime='2020-04-23 14:28:59'; //调试用
    if(autoOffTime){
      autoOffTime = autoOffTime.replace(/-/g,"/");
      this.data.countdownTimer = setInterval(()=>{
        // console.info(autoOffTime);
        let time = countDown(new Date(autoOffTime));
        this.setData({
          countdownTime:`${time.day}天${time.hour}小时${time.minute}分钟${time.second}秒`
        })
        if(time.day+time.hour+time.minute+time.second<=0){ //倒计时为负数停止计时器
          clearInterval(this.data.countdownTimer);
          this.setData({
            "goodDetail.g_status":2   //倒计时为0设置已下架，不允许购买
          });
          return;
        }
      },1000)
    }
  },
  // 立即购买跳转商品详情
  goDetail(e){
     const {id} = e.currentTarget.dataset;
      wx.navigateTo({
        url: `/subpages1/goodDetail/goodDetail?id=${id}`,
      })
  },
  // 跳转推广
  goPromotion(){
    let shareType = this.data.goodDetail.g_bill_image ? 'ider' : 'default';
    let shareBillImage = this.data.goodDetail.g_bill_image;
    wx.navigateTo({
      url: `/subpages1/promotion/promotion?gid=${this.data.goodId}&shareType=${shareType}&shareBillImage=${shareBillImage}`,
    })
  },
  //打开地图
  goNavigation:function(e){
    let [longitude,latitude] =  JSON.parse(e.currentTarget.dataset.location);
    wx.openLocation({
      latitude:Number(latitude),
      longitude:Number(longitude),
      scale:18,
    })
  },
  // 跳转商家详情页
  goMerchanInfo:function(e){
    // wanyiming
    if (app.globalData.checkData.check) {
      return false;
    }
    let mId = e.currentTarget.dataset.id;
    console.log(mId);
    wx.navigateTo({
      url: '/subpages1/merchantInfo/merchantInfo?mid=' + mId,
    })
  },
  //获取省市
  chooseRegion: function() {
    
    this.setData({
      showRegion: true,
    });
    
  },
  //获取省市
  emitHideRegion: function(e) {
    this.setData({
      showRegion: e.detail.showRegion,
      regionValue: e.detail.regionValue,
      province: e.detail.regionValue[0].name,
      city: e.detail.regionValue[1].name,
      district: e.detail.regionValue[2].name,
      town:e.detail.regionValue[3].name,
    });
    var that = this;
    var data = {
      map: 'applet_goods_stock',
      id: that.data.goodId,
      province: e.detail.regionValue[0].name,
      city: e.detail.regionValue[1].name,
      district: e.detail.regionValue[2].name,
      town:e.detail.regionValue[3].name,
    }
  },
  onLoad: function(e) {
    var that = this;
    
    console.log("-------页面参数",e)
    if (e && e.scene) {
      var scene = decodeURIComponent(e.scene).split('&');
      console.log(scene);
      var secneObj = {};
      for (var i = 0; i < scene.length; i++) {
        var arr = scene[i].split('=');
        var key = arr[0];
        secneObj[key] = arr[1];
      }
      e = secneObj;
    }
    if (e && e.id) {
      var goodId = e.id;
      that.setData({
        goodId: goodId
      })
    }
    if (e && e.laid) {
      var laid = e.laid;
      that.setData({
        laid: laid
      })
    }
    if (e && e.mid) {
      that.setData({
        mid: e.mid
      })
    }
    var res = wx.getSystemInfoSync();
    that.setData({
      winW: 750,
      winH: 1334,
      isShowOrdertip: !that.data.isShowOrdertip
    })
    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        if (plumSession != '') {
          console.log('查询到登录信息');
          var mid = that.data.mid ? that.data.mid : '';
          var goodId = that.data.goodId;
          app.globalData.requestUrl = app.getNewRequestUrl(mid);
          that.requestDetail(goodId);
          that.requestComment(goodId);
          that.getSlient();
          that.setData({
            isReady: true,
            isHasunionid: app.globalData.isHasunionid,
            haveVcmCard: app.globalData.haveVcmCard
          })
        } else {
          console.log('未查询到登录信息');
          app.wechatSq(that);
        }
      }
    } else {
      var mid = that.data.mid ? that.data.mid : '';
      var goodId = that.data.goodId;
      app.globalData.requestUrl = app.getNewRequestUrl(mid);
      that.requestDetail(goodId);
      that.requestComment(goodId);
      that.getSlient();
      that.setData({
        isReady: true,
        isHasunionid: app.globalData.isHasunionid,
        haveVcmCard: app.globalData.haveVcmCard
      })
    }
    
  },
  onShow: function() {
    var that = this;
    if (!app.globalData.plumSession) {
      // app.wechatSq(that);
    } else {
      that.setData({
        customerService: app.globalData.customerService ? app.globalData.customerService : '',
        isShowFenxiao: app.globalData.isdistrib ? app.globalData.isdistrib : '',
        isapply: app.globalData.isapply ? app.globalData.isapply : '',
        distribOpen: app.globalData.distribOpen ? app.globalData.distribOpen : '',
      })
      app.contactData(that);
      if (app.globalData.requestCartNum >= 0) {
        that.setData({
          cartNumber: app.globalData.requestCartNum
        })
      }
    }
    that.setData({
      isHasunionid: app.globalData.isHasunionid,
      haveVcmCard: app.globalData.haveVcmCard
    })
    that.getPartH();
  },
  initPage: function() {
    var that = this;
    that.onLoad();
    that.onShow();
  },
  getSlient: function() {
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient : '';
    that.setData({
      slient: slient
    })
  },
  hideGetuser: function() {
    var that = this;
    that.setData({
      isShowgetuser: false
    })
  },
  // 获取用户信息
  getuserInfo: function(e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      }
      app.getuserInfo(that, userdata, again);
    }
  },
  // 客服回复组件间传值
  getreplyData: function(e) {
    console.log(e.detail);
    this.setData(e.detail);
  },
  onReady: function() {
    var that = this;
    that.videoContext = wx.createVideoContext('myVideo');
  },
  onHide: function() {
    this.hideVideo();
  },
  //播放视频
  playVideo: function(e) {
    var that = this;
    if (app.globalData.isPlay) {
      bgMusicAudioContext.stop();
      app.globalData.curInfoMusicid = '';
      app.globalData.isPlay = false;
      app.globalData.isPlaynew = 'new';
    }
    that.setData({
      isShowVideo: true
    });
    that.videoContext.play();
  },
  // 关闭视频
  hideVideo: function() {
    var that = this;
    that.setData({
      isShowVideo: false
    })
  },
  requestDetail: function(goodId) {
    var that = this;

    
    //发起请求，获取列表列表
    var laid = that.data.laid;
    var data = {
      map: 'applet_goods_detail',
      gid: goodId
    };
    if (laid) {
      data.laid = laid;
    }
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var goodDetail = res.data.data;
          console.log('商品详情',goodDetail)
          
          if (goodDetail.video != '') {
            that.setData({
              video: goodDetail.video,
              videoShow: true,
            })
          }
          let name = goodDetail.name
          let price = goodDetail.price 
          if(goodDetail.g_source=='pft') {
            that.getTickets()
            let orderParameter = goodDetail.ticket_list[0]
            let need_datetime_picker = orderParameter.need_datetime_picker

            // if(orderParameter.user_price!==null&&orderParameter.user_price > 0) {
            //   goodDetail.price = orderParameter.user_price
            // }else {
            //   goodDetail.price = orderParameter.price
            // }
            // goodDetail.name = orderParameter.title
            that.TimeSelector(orderParameter.uuid)
            that.setData({
              need_time_picker:need_datetime_picker,
              orderParameter,
              modalOperaType: "buy",
              buyNumber: 1,
              in:null
            })
          }
          if(goodDetail.g_source=="travel"&&goodDetail.valid_type==0) {
            that.TimeSelection()
          }
          if(goodDetail.area_limit!=null) {
            that.GetAddress()
          }
          var seckill = goodDetail.seckill;
          var chooseGuige = that.data.chooseGuige;
          var stock = goodDetail.stock;
          /** 规格库存判断开始 **/
          if (res.data.data.formatList && res.data.data.formatList.length == 1) { //如果是单规格
            for (let i in res.data.data.formatList[0].value) {
              if (res.data.data.formatValueNew[res.data.data.formatList[0].value[i].name].stock == 0) {
                res.data.data.formatList[0].value[i].noCheck = true;
              }
            }
          }
          if (goodDetail.merchant_info && goodDetail.merchant_info.cm_logo) {
            goodDetail.merchant_info.cm_logo =   goodDetail.merchant_info.cm_logo.indexOf("http") == 0  ? goodDetail.merchant_info.cm_logo : 
            that.data.imgUrl + goodDetail.merchant_info.cm_logo;
          }
          goodDetail.reward = Number(goodDetail.reward).toFixed(2);

          // 商品详情
          if(goodDetail.detail) {
            goodDetail.detail = goodDetail.detail.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
          }
          // 购买须知
          if(goodDetail.buy_note) {
            goodDetail.buy_note = goodDetail.buy_note.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
          }
          

          /** 规格库存判断结束 **/
          //截止日期
          that.setData({
            nogood: 1,
            goodDetail: goodDetail,
            merchantInfo: goodDetail.merchant_info,
            cartNumber: goodDetail.cartNum,
            hasFormat: goodDetail.hasFormat,
            seckill: goodDetail.seckill,
            chooseGuige: {
              stock: stock
            },
            userBuyRecord: goodDetail.userBuyRecord,
            isShowCountdown:!!(goodDetail.g_time_show==1&&goodDetail.autoOffTime),  //是否显示倒计时
            price,
            name
          })
          
          that.setCountdownTimer(); //设置倒计时
          if (goodDetail.recommendGoods && goodDetail.recommendGoods.length > 0) {
            var recommendGoodslist = app.splitArrData(goodDetail.recommendGoods, 3);
            that.setData({
              recommendGoodslist: recommendGoodslist
            })
          }
          if (goodDetail.smallNum > 1) {
            that.setData({
              buyNumber: goodDetail.smallNum
            })
          }
          if (seckill == 1) {
            if (seckill == 1) {
              that.setData({
                seckillName: goodDetail.limit.name,
                goodType: 'seckill'
              })
            } else {
              clearInterval(that.data.intervarID);
            }
            that.countDjs();
          }
          // 富文本解析
          //var article = that.data.goodDetail.detail;
          //WxParse.wxParse('article', 'html', article, that, 5);
          var param = that.data.goodDetail.parameter;
          WxParse.wxParse('param', 'html', param, that, 5);
          //var buyNotes = that.data.goodDetail.buy_note;     //购买须知
          //WxParse.wxParse('buyNotes', 'html', buyNotes||'', that, 5)  //防止没得这个字段报错，设置个默认值
        } else {
          that.setData({
            nogood: 0,
            tips: res.data.em
          })
        }
      },
      complete: function() {
        wx.hideToast();
      }
    });
  },
  // 收藏商品
  addCollect: function() {
    var that = this;
    var gid = that.data.goodId;
    var goodDetail = that.data.goodDetail;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_mall_goodsCollect',
        gid: gid
      },
      success: function(res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          app.errorTip(that, res.data.data.msg, 2000);
          goodDetail.isCollect = res.data.data.isCollect;
          that.setData({
            goodDetail: goodDetail
          })
        } else {
          console.log(res.data);
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function() {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    })
  },
  requestComment: function(goodId) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_goods_comment_list',
        gid: goodId
      },
      success: function(res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            commentNum: res.data.data.total,
            commentList: res.data.data.list
          })
          console.log(that.data.commentList)
        } else {
          console.log(res.data);
        }
      },
      complete: function() {

      }
    });
  },
  toApplyFenxiao: function() {
    wx.navigateTo({
      url: '/pages/becomePartners/becomePartners'
    })
  },
  backShouye: function() {
    app.backHome();
  },
  backCart: function() {
    wx.navigateTo({
      url: '/pages/mycartTab/mycartTab'
    })
  },
  countDjs: function() {
    var that = this;
    // console.log(that.data.goodDetail.limit);
    if (that.data.goodDetail.seckill == 1) {
      var endTime = that.data.goodDetail.limit.endTime * 1000;
      var startTime = that.data.goodDetail.limit.startTime * 1000;
    }
    var curtime = new Date(); //避免页面渲染倒计时的时候出现一秒的延迟。
    var startSpan1 = startTime - curtime;
    var endSpan2 = endTime - curtime;
    if (startSpan1 > 0) {
      that.setData({
        start: '开始',
      })
      that.djs(startSpan1);
    } else {
      that.setData({
        start: '结束',
      })
      that.djs(endSpan2);
    }
    that.data.intervarID = setInterval(function() {
      var nowTime = new Date();
      var startSpan = startTime - nowTime;
      var endSpan = endTime - nowTime;
      if (startSpan > 0) {
        that.setData({
          start: '开始',
        })
        that.djs(startSpan);
      } else {
        that.setData({
          start: '结束',
        })
        that.djs(endSpan);
      }
    }, 1000)
    // }

  },
  djs: function(time) {
    var that = this;
    var leftTime = time;
    that.setData({
      leftTime: leftTime
    })
    if (leftTime > 0) {
      var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 1000 / 60 % 60, 10); //计算剩余的分钟 
      var seconds = parseInt(leftTime / 1000 % 60, 10); //计算剩余的秒数 
      days = days < 10 ? '0' + days : days;
      // console.log(days);
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      that.setData({
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      })
      if (days == '00' && hours == '00' && minutes == '00' && seconds == '00') {
        clearInterval(that.data.intervarID);
      }
    } else {
      that.setData({
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00',
      })
    }
  },
  chooseGuige: function(e) {
    var that = this;
    var findex = e.currentTarget.dataset.findex;
    var index = e.currentTarget.dataset.index;
    var disabled = e.currentTarget.dataset.disabled; //是否可以选择
    if (disabled) return;
    var goodDetail = that.data.goodDetail;
    var checkFormat = [];
    for (var i = 0; i < goodDetail.formatList[findex].value.length; i++) {
      if (index == i) {
        goodDetail.formatList[findex].value[index].checked = !goodDetail.formatList[findex].value[index].checked;
        if (findex == 0 && goodDetail.formatList[findex].value[index].checked) {
          var curImgformat = goodDetail.formatList[0].value[index]; //当前选择规格的小图展示
          console.log('当前规格索引', findex, index);
          console.log('当前规格图片上一级', goodDetail.formatList[0]);
          console.log('当前规格图片', curImgformat);
          that.setData({
            curImgformat: curImgformat
          })
        } else {
          if (findex == 0) {
            that.setData({
              curImgformat: ''
            })
          }
        }
      } else {
        goodDetail.formatList[findex].value[i].checked = false;
      }
    }
    for (var i = 0; i < goodDetail.formatList.length; i++) {
      for (var j = 0; j < goodDetail.formatList[i].value.length; j++) {
        if (goodDetail.formatList[i].value[j].checked) {
          checkFormat.push(goodDetail.formatList[i].value[j]);
        }
      }
    }
    console.log('选择的规格', checkFormat);
    /** 规格库存判断开始 **/
    for (let k in goodDetail.formatList) {
      for (let n in goodDetail.formatList[k].value) {
        goodDetail.formatList[k].value[n].noCheck = false
      }
    }

    //存放规格数据的对象
    for (let i in goodDetail.formatValueNew) {
      let noStockArr = []; //没有库存的规格数组
      let formatValueItem = i.split('-');
      // console.log('分割规格名字为数组', formatValueItem);
      switch (checkFormat.length) { //选择的是第几个规格
        case 1:
          if (formatValueItem.indexOf(checkFormat[0].name) != -1 && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 2) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            noStockArr = formatValueItem;
          } else if (goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 1) {
            noStockArr.push(i);
          } else if (formatValueItem.indexOf(checkFormat[0].name) != -1 && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 3) {
            noStockArr = [];
          }
          break;
        case 2:
          if ((formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValueItem.indexOf(checkFormat[1].name) != -1) && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 3) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            noStockArr = formatValueItem;
          } else if ((formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1) && goodDetail.formatValueNew[i]['stock'] == 0 && goodDetail.formatList.length == 2) {
            if (formatValueItem.indexOf(checkFormat[0].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            }
            if (formatValueItem.indexOf(checkFormat[1].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            }
            noStockArr = formatValueItem;
          }
          // console.log(noStockArr);
          break;
        case 3:
          if (goodDetail.formatValueNew[i]['stock'] == 0 && (formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1 || formatValueItem.indexOf(checkFormat[2].name) != -1)) {
            for (let q in checkFormat) {
              formatValueItem[formatValueItem.indexOf(checkFormat[q].name)] = '';
            }
            if (formatValueItem[0] === '') {
              formatValueItem[1] = formatValueItem[2] = formatValueItem[1] + formatValueItem[2]
            }
            if (formatValueItem[1] === '') {
              formatValueItem[0] = formatValueItem[2] = formatValueItem[0] + formatValueItem[2]
            }
            if (formatValueItem[2] === '') {
              formatValueItem[0] = formatValueItem[1] = formatValueItem[0] + formatValueItem[1]
            }
            console.log(formatValueItem);
            noStockArr = formatValueItem
          }
          break;
      }

      //所有规格与没有库存的规格作对比，将库存为0的规格不能选中
      for (let k in goodDetail.formatList) {
        for (let n in goodDetail.formatList[k].value) {
          // console.log('没有库存的规格', noStockArr);
          if (noStockArr.indexOf(goodDetail.formatList[k].value[n].name) != -1) {
            goodDetail.formatList[k].value[n].noCheck = true
          }
        }
      }

    }
    // 单规格库存判断
    if (goodDetail.formatList.length == 1) {
      for (let i in goodDetail.formatList[0].value) {
        if (goodDetail.formatValueNew[goodDetail.formatList[0].value[i].name].stock == 0) {
          goodDetail.formatList[0].value[i].noCheck = true;
        }
      }
    }
    /** 规格库存判断结束 **/
    console.log(goodDetail.formatList);
    that.setData({
      goodDetail: goodDetail,
      checkFormat: checkFormat
    })
    if (checkFormat.length == goodDetail.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
        if (i < checkFormat.length - 1) {
          formatName += '-';
        }
      }
      console.log('规格名称', formatName);

      console.log(goodDetail.formatValueNew);
      var chooseGuige = goodDetail.formatValueNew[formatName];
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    } else {
      that.setData({
        chooseGuige: {
          stock: goodDetail.stock
        }
      })
    }
    var buyNumber = that.data.buyNumber;
    var stock = that.data.chooseGuige.stock;
    if (buyNumber >= stock) {
      that.setData({
        buyNumber: stock
      })
    }
  },
  addcart: function(e) {
    var that = this;
    if(that.data.goodDetail.g_source=='travel'||that.data.goodDetail.g_source=='pft') {
      wx.showToast({
        title: '加入购物车失败',
        icon:'none',
        duration:2000
      })
      return;
    }
    if ((that.data.goodDetail.area_limit||that.data.goodDetail.g_source=='yanxuan'||that.data.goodDetail.g_source=='yx'||that.data.goodDetail.g_source=='jd') && that.data.province == '') {
      wx.showModal({
        title: '提示',
        content: '请选择配送区域',
        showCancel: true
      })
      return;
    }
  
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    that.setData({
      isShowModal: true,
      modalOperaType: "addcart",
      buyNumber: 1
    })
  },
  //立即预约
  TicketBooking(e) {
    let {goodDetail, orderParameter} = this.data
    goodDetail.name = orderParameter.title
    if(orderParameter.user_price!==null&&orderParameter.user_price > 0) {
      goodDetail.price = orderParameter.user_price
    }else {
      goodDetail.price = orderParameter.price
    }
    if(this.data.orderParameter==null) {
      wx.showModal({
        title: '提示',
        content: '请选择门票类型',
        showCancel: true
      })
      this.setData({
        intoView: 'comment',
      })
    }else {
      this.setData({
        isShowModal: true,
        modalOperaType: "buy",
        buyNumber: 1,
        goodDetail
      })
    }
  },
  nowbuy: function() {
    var that = this;
    if ((that.data.goodDetail.area_limit||that.data.goodDetail.g_source=='yanxuan'||that.data.goodDetail.g_source=='yx'||that.data.goodDetail.g_source=='jd') && that.data.province == ''){
      wx.showModal({
        title: '提示',
        content: '请选择配送区域',
        showCancel: true
      })
      return;
    }

  
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    that.setData({
      isShowModal: true,
      modalOperaType: "buy",
      buyNumber: 1
    })},
  hideModal: function() {
    var that = this;
    let {goodDetail,name,price} =that.data
    goodDetail.name = name
    goodDetail.price = price
    that.setData({
      isShowModal: false,
      goodDetail
    })
  },
  changeNum: function(e) {
    var that = this;
    var modalOperaType = that.data.modalOperaType;
    var userBuyRecord = that.data.userBuyRecord;
    var type = e.currentTarget.dataset.type;
    var buyNum = parseInt(that.data.buyNumber);
    var stock = that.data.chooseGuige.stock;
    var purchase = that.data.goodDetail.purchase;
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
      }
      if (buyNum < stock) {
        if (modalOperaType == 'addcart') {
          let curusenum = userBuyRecord.canBuy - userBuyRecord.cartNum;
          if (buyNum < curusenum) {
            buyNum++;
          } else {
            app.errorTip(that, '超出限购数量', 2000);
          }
        } else if (modalOperaType == 'buy') {
          if (buyNum < userBuyRecord.canBuy) {
            buyNum++;
          } else {
            app.errorTip(that, '超出限购数量', 2000);
          }
        }
      } else {
        buyNum = stock;
      }
    } else {
      var smallNum = that.data.goodDetail.smallNum > 1 ? that.data.goodDetail.smallNum : 1;
      if (buyNum > smallNum) {
        buyNum--;
      } else {
        buyNum = smallNum;
      }
    }

    that.setData({
      buyNumber: buyNum
    })
  },
  numChange: function(e) {
    var that = this;
    var stock = that.data.chooseGuige.stock;
    var val = e.detail.value;
    val = val.replace(/\D/g, '');
    if ((parseInt(val)) > parseInt(stock)) {
      that.setData({
        buyNumber: stock
      })
    } else {
      that.setData({
        buyNumber: val
      })
    }
  },
  confirmAddcart: function(e) {
    var that = this;
    var suid = app.globalData.suid;
    var gid = e.target.dataset.gid;
    var gfid = that.data.chooseGuige.id;
    var num = parseInt(that.data.buyNumber);
    var isFormat = that.data.hasFormat;
    var stock = parseInt(that.data.chooseGuige.stock);
    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: num,
      add: 1,
      province:that.data.province,
      city:that.data.city,
      district:that.data.district,
      town:that.data.town
    }
    if (isFormat && !gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!data.num || data.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + data.num);
    if (data.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          wx.showToast({
            title: res.data.data.msg,
            icon: 'success',
            duration: 2000,
          })
          that.hideModal();
          that.setData({
            cartNumber: res.data.data.cartNum
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  nextStep: function() {
    var that = this;
    var gfid = that.data.chooseGuige.id;
    var orderParameter = that.data.orderParameter;
    var isFormat = that.data.hasFormat;
    var orderArr = [];
    var orderObj = {};
    let goodDetail = that.data.goodDetail
    orderObj.gid = that.data.goodDetail.id;
    orderObj.gfid = that.data.chooseGuige.id;
    orderObj.num = parseInt(that.data.buyNumber);
    var stock = parseInt(that.data.chooseGuige.stock);
    orderArr.push(orderObj);
    var data = {};
    data.map = 'applet_order_create_v2';
    data.province = that.data.province;
    data.city = that.data.city;
    data.district =that.data.district;
    data.town = that.data.town
    data.buys = encodeURI(JSON.stringify(orderArr));
    if(orderParameter!==null) {
      data.aid = orderParameter.aid
      data.settle_price = orderParameter.settle_price
      if(orderParameter.user_price!==null&&orderParameter.user_price > 0) {
        data.pft_price = orderParameter.user_price
      }else {
        data.pft_price = orderParameter.price
      }
      data.ticket_id = orderParameter.uuid
      data.title = orderParameter.title
      if(orderParameter.playtime!==undefined) {
        data.playtime = orderParameter.playtime
      }else {
        data.playtime = ''
      }
      
      data.num = parseInt(that.data.buyNumber);
      if(that.data.goodDetail.g_source == 'pft') {
        data.pft = true
      }
    }
    if(goodDetail.g_source=='travel'&&goodDetail.valid_type==0) {
      if(that.data.playtime) {
        data.playtime = that.data.playtime
      }else {
        wx.showToast({
          title: '请选择时间',
          icon:'none',
          duration:2000
        })
        return;
      }
     
    }
    if (isFormat && !gfid) {
      console.log('请选择商品规格！');
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!orderObj.num || orderObj.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + orderObj.num);
    if (orderObj.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    console.log(data);
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    console.log('立即购买',data)
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        if (res.data.ec == 200) {
          let {common,trade_list} = res.data;
          let orderInfo = {common,trade_list};
          wx.setStorage({
            key: "submitOrder",
            data: orderInfo,
            success: function(res) {
              console.log(res);
              if(that.data.goodDetail.g_source == 'pft') {
                wx.navigateTo({
                  url: '/pages/waitBuyerPay/waitBuyerPay?source=pft'
                })
              }else {
                wx.navigateTo({
                  url: '/pages/waitBuyerPay/waitBuyerPay'
                })
              }
            }
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function() {
        wx.hideToast();
      }
    });
  },
  toEvaluateList: function() {
    var that = this;
    var goodid = that.data.goodId;
    wx.navigateTo({
      url: '/pages/evaluateList/evaluateList?goodid=' + goodid
    })
  },
  peiviewImg: function(e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //单张图片预览
  singlePeiviewImg: function(e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  showSharemodal: function() {
    this.setData({
      isShowshare: true
    })
  },
  hideSharemodal: function() {
    this.setData({
      isShowshare: false
    })
  },
  toGoodposter: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var laid = that.data.laid;
    var url = '/subpages/goodPoster/goodPoster?id=' + id + '&type=good';
    if (laid) {
      url = '/subpages/goodPoster/goodPoster?id=' + id + '&type=seckill&laid=' + laid;
    }
    wx.navigateTo({
      url: url
    })
    this.hideSharemodal();
  },
  toGoodparameter: function(e) {
    var parameter = e.currentTarget.dataset.param;
    wx.setStorage({
      key: "goodParameter",
      data: parameter,
      success: function() {
        wx.navigateTo({
          url: '/subpages/goodParameter/goodParameter',
        })
      }
    })
  },
  // VR视图
  toWebview: function(e) {
    var that = this;
    var vrurl = e.currentTarget.dataset.vrurl;
    var cover = e.currentTarget.dataset.cover;
    var title = e.currentTarget.dataset.title;
    var vrInfo = {
      vrurl: vrurl,
      cover: cover ? cover : '',
      title: title ? title : ''
    }
    wx.setStorage({
      key: 'webviewUrl',
      data: vrInfo,
      success: function() {
        wx.navigateTo({
          url: '/pages/commonView/commonView',
        })
      }
    })
  },
  goodDetail: function(e) {
    var goodId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subpages/goodDetailtwo/goodDetailtwo?id=' + goodId
    })
  },
  jumpPart: function(e) {
    var curPart = e.currentTarget.dataset.part;
    this.setData({
      intoView: curPart,
      curPart: curPart
    })
    console.log(this.data.intoView);
  },
  getPartH: function() {
    var that = this;
    var query = wx.createSelectorQuery();
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winH: 1334 
        })
        query.select('#toppart').boundingClientRect(function(rect) {
          if (rect) {
            that.setData({
              topPartH: rect.height
            })
          }
        }).exec()
        query.select('#bottompart').boundingClientRect(function(rect) {
          if (rect) {
            that.setData({
              bootomOperaH: rect.height
            })
          }
        }).exec()
      }
    })
  },
  goodscroll: function(e) {
    var that = this;
    var query = wx.createSelectorQuery();
    query.selectAll('.part-con').boundingClientRect(function(rects) {
      var newRect = [];
      rects.forEach(function(rect) {
        var obj = {
          id: rect.id,
          top: rect.top,
          bottom: rect.bottom,
          height: rect.height
        }
        newRect.push(obj);
      })
      that.getShowpart(newRect);
    }).exec()
  },
  getShowpart: function(newRect) {
    var that = this;
    var winH = that.data.winH;
    var topH = that.data.topPartH;
    var bottomH = that.data.bootomOperaH;
    var scrollViewH = winH - topH - bottomH;
    for (var i in newRect) {
      var item = newRect[i];
      if (item.bottom - topH < 0) {
        item.percent = 0;
      } else {
        if (item.bottom - winH > 0) {
          if (item.top - topH < scrollViewH) {
            item.percent = (scrollViewH - (item.top - 40)) / scrollViewH * 100;
          } else {
            item.percent = 0;
          }
        } else {
          if (item.top - topH < 0) {
            if (item.height < scrollViewH) {
              item.percent = 100 - 1;
            } else {
              item.percent = ((item.bottom - topH) / scrollViewH) * 100;
            }
          } else {
            item.percent = (scrollViewH - (item.top - 40)) / scrollViewH * 100;
          }
        }
      }
    }
    newRect.sort(function(a, b) {
      return b.percent - a.percent;
    })
    that.setData({
      curPart: newRect[0].id
    })
  },
  toggleGoodshow: function(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    that.setData({
      curshow: type
    })
  },
  //打开折扣卡
  openBuyMenberCard: function(e) {
    // todo wanyiming
    if (app.globalData.checkData.check) {
      return false;
    }
    var that = this;
    var type = e.currentTarget.dataset.type;
    if (type == 0) {
      wx.navigateTo({
        url: '/subpages/memberCard/memberCard'
      })
    } else if (type == 1) {
      wx.navigateTo({
        url: '/subpages/buyMenberCard/buyMenberCard'
      })
    } else if (type == 2) {
      wx.navigateTo({
        url: '/subpages/storeMemberPage/storeMemberPage'
      })
    } else if (type == 3) {
      wx.navigateTo({
        url: '/subpages/walletRecharge/walletRecharge?from=slide'
      })
    }
  },
  showPoster: function() {
    var that = this;
    that.setData({
      isShowposter: true
    })
    var isDrawfinish = that.data.isDrawfinish;
    if (isDrawfinish) {
      return;
    }
    app.requestShareinfo(that);
  },
  hidePoster: function() {
    var that = this;
    that.setData({
      isShowposter: false
    })
  },
  saveImage: function() {
    app.saveImage(this)
  },
  groupDetail: function(e) {
    var goodid = e.currentTarget.dataset.goodid;
    wx.navigateTo({
      url: '/subpages1/groupGoodDetail/groupGoodDetail?goodid=' + goodid
    })
  },
  toFxposter: function() {
    var id = this.data.goodDetail.id;
    wx.navigateTo({
      url: '/subpages0/distribPoster/distribPoster?id=' + id,
    })
  },
  // 优惠券
  toCouponlist: function() {
    wx.navigateTo({
      url: '/subpages/couponList/couponList'
    })
  },
  stoptouchmove: function(e) {
    console.log(e,'取消')
  },

  // 生成海报图
  peiviewPoster: function() {
    var that = this;
    var id = that.data.goodId;
    var detailInfor = that.data.goodDetail;
    var shareType = detailInfor.g_bill_image ? 'ider' : 'default'; 
    var data = {
      map: shareType == 'ider' ? 'applet_goods_share_poster_v2' : 'applet_goods_share_poster',
      id: id
    }
    wx.showLoading({
      title: '海报生成中，请等待...',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        if (res.data.ec == 200) {
          if (shareType == 'ider') {
            console.log('海报二维码',res.data.data)
            let memberSahreImg = res.data.data.memberShareImg;
            wx.getImageInfo({
              src: memberSahreImg,
              success: function (r) {
                let merchantPage = r.path;
                that.creatIderShareImg(res.data.data, merchantPage);
              }
            })
          } else {
            // 之前的代码
            var detailInfo = res.data.data;
            var curimg = detailInfo.shareImg;
            var imgs = [];
            imgs.push(curimg);
            wx.previewImage({
              current: curimg, // 当前显示图片的http链接
              urls: imgs // 需要预览的图片http链接列表
            });
          }
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function() {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  // Ider分享图
  creatIderShareImg: function (result, merchantShareImg) {
    var that = this;
    console.log('分享图数据', result);
    console.log('获取商品数据', that.data.goodDetail);
    var detailInfor = that.data.goodDetail;
    var shareType = detailInfor.g_bill_image ? 'ider' : 'default'; 
    var cover = detailInfor.g_bill_image ? detailInfor.g_bill_image : (detailInfor.coverDown ? detailInfor.coverDown : detailInfor.cover);

    let winW = that.data.winW;
    let winH = that.data.winH;
    console.log(winW,winH)
    that.setData({
      canvasW: winW,
      canvasH: winH
    }); 
    
    if (shareType == 'ider') {
        // 自定义分享海报
      wx.getImageInfo({
        src: cover,
        success: function (res) {
            var shareCanvas = wx.createCanvasContext('share-cover');
            shareCanvas.drawImage(res.path, 0, 0, winW, winH);
            // 首先设定二维码大小
            let qrWidth = winW / 10;
            let msH = winH - (winH / 10) - (qrWidth / 2) - 10;
            console.log('二维码大小',qrWidth,msH)
            shareCanvas.drawImage(merchantShareImg, qrWidth / 2, msH, qrWidth * 2, qrWidth * 2);
            shareCanvas.draw(false, function (e) {
              wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: winW,
                height: winH,
                canvasId: 'share-cover',
                fileType: 'jpg',
                quality: 1,
                success: function (res) {
                  var tempFilePathShow = res.tempFilePath;
                  console.log('海报',tempFilePathShow)
                  that.setData({
                    shareCover: tempFilePathShow
                  });
                  var imgs = [];
                  imgs.push(tempFilePathShow);
                  wx.previewImage({
                    current: tempFilePathShow, // 当前显示图片的http链接
                    urls: imgs // 需要预览的图片http链接列表
                  })
                  wx.hideLoading();
                },
                fail: function () {
                  wx.hideLoading();
                }
              })
            });
        }
      });
      return false;
    } else {
        // 默认分享海报
    }
    return false;
  },
  onShareAppMessage: function() {
    var that = this;
    var goodDetail = that.data.goodDetail;
    var mid = app.globalData.userInfo.mid;
    console.log('mid' + app.globalData.userInfo.mid)
    var goodid = that.data.goodId;
    var title = goodDetail.limitShareTitle ? goodDetail.limitShareTitle : goodDetail.name;
    var cover = goodDetail.limitShareImg ? goodDetail.limitShareImg : goodDetail.cover;
    that.hideSharemodal();
    app.getPoint(that);
    return {
      title: title,
      imageUrl: that.data.shareCover ? that.data.shareCover : cover,
      path: '/subpages1/goodDetail/goodDetail?enterfrom=share&id=' + goodid + '&mid=' + mid
    }
  },
  cllaPhone: function(e) { // 拨打电话
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  //打开日历
  onDisplay(e) {
    let id = e.currentTarget.dataset.id;
    let dateOfUse = this.data.dateOfUse
    let orderParameter= this.data.orderParameter
    if(dateOfUse) {
      orderParameter.playtime = dateOfUse.data
      orderParameter.price = dateOfUse.price
    }
    
    if(id==0) {
      this.setData({
        dataI:0,
        orderParameter:orderParameter,
        selection:{
          date:'更多',
          price:'时间'
        },
        in:null
      })
    }else {
      this.setData({ 
        show: true,
        isShowModal:false
      })
    }
    ;
  },
  closeCalendar() {
    this.setData({ 
      show: false,
      isShowModal:true
    });
  },
  getCalendarData(e) { // 监听日历数据
    console.log('监听日历',e)
    let detail = e.detail
    let orderParameter = this.data.orderParameter
    let goodDetail= this.data.goodDetail
    let dateOfUse = this.data.dateOfUse
    let selection ={}
    console.log('orderParameter',detail)
    if(detail.item!=null) {
      if(detail.item.price!==undefined) {
        if(dateOfUse.day==detail.item.date) {
          this.setData({
            show:false,
            isShowModal:true,
            dataI:0,
            in:detail.in
          })
        }else {
          if(detail.currentMonth<10) {
            detail.currentMonth='0'+detail.currentMonth
          }
          if(detail.item.date<10) {
            detail.item.date='0'+detail.item.date
          }
          orderParameter.playtime = detail.currentYear+'-'+detail.currentMonth+'-'+detail.item.date
          orderParameter.price = detail.item.price
          goodDetail.price = detail.item.price
          selection.date = detail.currentMonth+'-'+detail.item.date
          selection.price = detail.item.price
          this.setData({
            orderParameter:orderParameter,
            goodDetail:goodDetail,
            selection:selection,
            show:false,
            isShowModal:true,
            dataI:1,
            in:detail.in
          })
        } 
      }else {
        let playtime = detail.currentYear+'-'+detail.currentMonth+'-'+detail.item.date
        selection.date = detail.currentMonth+'-'+detail.item.date
        selection.price = detail.currentYear
        
        this.setData({
          orderParameter:orderParameter,
          selection,
          show:false,
          isShowModal:true,
          dataI:1,
          in:detail.in,
          playtime
        })
      }
    }
  },
  //折叠面板
  foldingPanel(e) {
    let i = null
    if(this.data.ticketI == e.currentTarget.dataset.i) {
      i = null
    }else {
      i = e.currentTarget.dataset.i
    }
    this.setData({
      ticketI:i
    })
  },
  GetAddress() {//获取地址
    let that = this
    let data = {
      map:'applet_address_get_by_pid',
      pid: 0
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      method:'GET',
      success: function(res) {
        that.setData({
          area:res.data.data
        })
      }
    })
  }
})
